package com.utils;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson2.JSONObject;
import com.domain.entity.User;
import com.exception.ServiceException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.rmi.ServerException;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt工具类
 */
public class JWTUtils {

    /**
     * 令牌自定义标识
     */
    public static final String HEADER = "Authorization";

    /**
     * 令牌前缀
     */
    public static final String TOKEN_PREFIX = "Bearer ";

    /**
     * 用于生成jwt的key
     */
    public static final String KEY = "abc";

    /**
     * 用户信息存放在payload中的key
     */
    public static final String PAYLOAD_KEY = "user";

    /**
     * 根据用户信息生成对应的token
     *
     * @param user 用户信息
     * @return 生成的token
     */
    public static String createToken(User user) {
        // 1. 判断用户是否为空
        if (user == null) {
            // 抛出异常
            throw new ServiceException("token解析错误");
        }
        // 2. 将用户信息设置进jwt的payload中
        Map<String, Object> payloadMap = new HashMap<>();
        payloadMap.put(PAYLOAD_KEY, user);
        // 3. 创建token
        return JWTUtil.createToken(payloadMap, KEY.getBytes());
    }

    /**
     * 解析token并转换为用户信息
     *
     * @param token token字符串
     * @return 用户信息
     */
    public static User parseToken(String token) {
        // 1. 将token解析为jwt对象
        JWT jwt = JWTUtil.parseToken(token);
        // 2. 获取payload
        Object userPayload = jwt.getPayload(PAYLOAD_KEY);
        if (userPayload == null) {
            // 为空,抛出异常
            throw new ServiceException("token解析错误");
        }

        // 3. 将object转化为User对象
        return JSONObject.parseObject(JSONObject.toJSONString(userPayload), User.class);
    }

    public static ServletRequestAttributes getRequestAttributes() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }

    /**
     * 获取当前登录用户
     *
     * @return 当前登录用户
     */
    public static User getCurrentUser() {
        // 1. 获取请求体
        HttpServletRequest request = getRequestAttributes().getRequest();

        // 2. 获取指定header的值
        String header = request.getHeader(HEADER);
        if (StringUtils.isBlank(header)) {
            // 当前访问用户未登录
            return null;
        }

        // 3. 去除token的前缀
        String token = header.replace(TOKEN_PREFIX, "");

        // 4. 解析获取的token
        return parseToken(token);
    }


    public static void main(String[] args) throws ServerException {
        User user = new User();
        user.setId(1);
        user.setPwd("55555");
        user.setUserName("5555");
        String token = createToken(user);

        System.out.println("生成的token:" + token);

        User user1 = parseToken(token);
        System.out.println("解析的结果:" + JSONObject.toJSONString(user1));
    }

}
